// 添加日志系统
const logger = {
    debug: false,
    enableDebug: function() {
        this.debug = true;
        console.log('调试日志已启用');
    },
    info: function(message, ...args) {
        if (this.debug) {
            console.log(`[INFO] ${message}`, ...args);
        }
    },
    error: function(message, ...args) {
        console.error(`[ERROR] ${message}`, ...args);
    }
};

// 快捷键录制相关变量
let isRecording = false;
let currentShortcutInput = null;
const pressedKeys = new Set();
let currentKeyDownHandler = null;
let currentClickHandler = null;

// 全局事件处理函数
function handleGlobalKeyDown(keyEvent) {
    if (!isRecording || !currentShortcutInput) return;
    
    // 阻止默认行为
    keyEvent.preventDefault();
    
    // 获取按键组合
    const key = keyEvent.key.toLowerCase();
    if (key === 'escape') {
        // ESC键取消录制
        finishRecording();
        return;
    }
    
    // 添加修饰键
    if (keyEvent.ctrlKey) pressedKeys.add('ctrl');
    if (keyEvent.shiftKey) pressedKeys.add('shift');
    if (keyEvent.altKey) pressedKeys.add('alt');
    if (keyEvent.metaKey) pressedKeys.add('meta');
    
    // 添加主键
    if (!['control', 'shift', 'alt', 'meta'].includes(key)) {
        pressedKeys.add(key);
    }
    
    // 更新显示
    const shortcut = Array.from(pressedKeys).join('+');
    currentShortcutInput.value = shortcut;
}

function handleGlobalKeyUp(keyEvent) {
    if (!isRecording || !currentShortcutInput) return;
    
    const key = keyEvent.key.toLowerCase();
    if (['control', 'shift', 'alt', 'meta'].includes(key)) {
        pressedKeys.delete(key);
    }
    
    // 更新显示
    const shortcut = Array.from(pressedKeys).join('+');
    currentShortcutInput.value = shortcut;
}

function handleGlobalClick(clickEvent) {
    if (!isRecording || !currentShortcutInput) return;
    
    // 如果点击的不是快捷键输入框或其子元素
    if (!currentShortcutInput.contains(clickEvent.target) && clickEvent.target !== currentShortcutInput) {
        finishRecording();
    }
}

function finishRecording() {
    if (!currentShortcutInput) return;
    
    currentShortcutInput.classList.remove('recording');
    currentShortcutInput.setAttribute('placeholder', '点击此处设置快捷键');
    
    // 移除全局事件监听器
    document.removeEventListener('keydown', handleGlobalKeyDown);
    document.removeEventListener('keyup', handleGlobalKeyUp);
    document.removeEventListener('click', handleGlobalClick);
    
    // 重置状态
    isRecording = false;
    pressedKeys.clear();
    currentShortcutInput = null;
}

document.addEventListener('DOMContentLoaded', async () => {
    // 获取按钮元素
    const translatePageBtn = document.getElementById('translatePage');
    const summarizePageBtn = document.getElementById('summarizePage');
    const translateAndSummarizeBtn = document.getElementById('translateAndSummarize');
    const importDataBtn = document.getElementById('importData');
    const exportDataBtn = document.getElementById('exportData');
    
    // 获取设置选项
    const autoTranslateCheckbox = document.getElementById('autoTranslate');
    const saveHistoryCheckbox = document.getElementById('saveHistory');
    const apiKeyInput = document.getElementById('apiKey');
    const baseUrlInput = document.getElementById('baseUrl');
    const modelNameInput = document.getElementById('modelName');
    const saveSettingsBtn = document.getElementById('saveSettings');
    const addUrlPatternBtn = document.getElementById('addUrlPattern');
    const urlPatternsContainer = document.getElementById('urlPatterns');
    
    // 获取加载状态元素
    const loadingElement = document.getElementById('loading');
    const progressBarFill = document.querySelector('.progress-bar-fill');
    
    // 检查必要的元素是否存在
    if (!translatePageBtn || !summarizePageBtn || !translateAndSummarizeBtn || !importDataBtn ||
        !exportDataBtn || !autoTranslateCheckbox || !saveHistoryCheckbox || !apiKeyInput || !baseUrlInput ||
        !modelNameInput || !saveSettingsBtn || !addUrlPatternBtn || !urlPatternsContainer ||
        !loadingElement || !progressBarFill) {
        console.error('某些必要的DOM元素未找到');
        return;
    }
    
    // 加载保存的设置
    chrome.storage.sync.get(['autoTranslate', 'saveHistory', 'apiKey', 'baseUrl', 'modelName', 'urlPatterns'], (result) => {
        autoTranslateCheckbox.checked = result.autoTranslate || false;
        saveHistoryCheckbox.checked = result.saveHistory || false;
        apiKeyInput.value = result.apiKey || '';
        baseUrlInput.value = result.baseUrl || 'https://platform.moonshot.cn/v1';
        modelNameInput.value = result.modelName || 'moonshot-v1-8k';
        
        // 加载URL模式配置
        if (result.urlPatterns && result.urlPatterns.length > 0) {
            // 清空现有列表
            urlPatternsContainer.innerHTML = '';
            
            // 添加每个URL模式
            result.urlPatterns.forEach(pattern => {
                addUrlPatternRow(pattern);
            });
            
            console.log('已加载URL模式配置:', result.urlPatterns);
        } else {
            console.log('没有保存的URL模式配置');
        }
    });
    
    // 设置快捷键监听器
    setupShortcutListener();
    
    // 修改添加URL模式行的函数
    function addUrlPatternRow(pattern = null) {
        const row = document.createElement('div');
        row.className = 'url-pattern-row';
        
        // 创建按钮名称容器（可点击区域）
        const nameContainer = document.createElement('div');
        nameContainer.className = 'pattern-name-container';
        nameContainer.textContent = pattern ? pattern.buttonName || pattern.pattern : '新配置';
        nameContainer.addEventListener('click', () => {
            showUrlPatternModal(pattern);
        });
        
        // 创建编辑按钮
        const editBtn = document.createElement('button');
        editBtn.className = 'edit-btn';
        editBtn.title = '编辑';
        editBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            showUrlPatternModal(pattern);
        });
        
        // 创建删除按钮
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-btn';
        deleteBtn.title = '删除';
        deleteBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            row.remove();
            saveUrlPatterns();
        });
        
        // 添加所有元素到行
        row.appendChild(nameContainer);
        row.appendChild(editBtn);
        row.appendChild(deleteBtn);
        
        // 存储完整配置数据
        row.dataset.pattern = pattern ? pattern.pattern : '';
        row.dataset.backendUrl = pattern ? pattern.backendUrl : '';
        row.dataset.shortcut = pattern ? pattern.shortcut : '';
        row.dataset.buttonName = pattern ? pattern.buttonName : '';
        row.dataset.contentType = pattern ? pattern.contentType : 'cookies';
        if (pattern && pattern.contentType === 'custom') {
            row.dataset.customText = pattern.customText;
        }
        
        urlPatternsContainer.appendChild(row);
    }
    
    // 快捷键录制功能增强
    function setupShortcutRecording() {
        // 快捷键输入字段点击处理
        document.addEventListener('click', event => {
            const shortcutInput = event.target.closest('.shortcut-input');
            if (shortcutInput) {
                // 如果已经在录制，先结束之前的录制
                if (isRecording) {
                    finishRecording();
                }
                
                // 开始新的录制
                isRecording = true;
                currentShortcutInput = shortcutInput;
                shortcutInput.classList.add('recording');
                shortcutInput.setAttribute('placeholder', '按下快捷键...');
                pressedKeys.clear();
                
                // 添加全局事件监听器
                document.addEventListener('keydown', handleGlobalKeyDown);
                document.addEventListener('keyup', handleGlobalKeyUp);
                document.addEventListener('click', handleGlobalClick);
            } else {
                // 如果点击了其他区域，结束所有录制
                finishRecording();
            }
        });
    }
    
    // 显示URL模式编辑模态框
    function showUrlPatternModal(pattern = null) {
        const modal = document.getElementById('urlPatternModal');
        const form = modal.querySelector('form');
        const buttonNameInput = document.getElementById('buttonName');
        const patternInput = document.getElementById('pattern');
        const backendInput = document.getElementById('backend');
        const shortcutInput = document.getElementById('shortcut');
        const shortcutClearBtn = shortcutInput.nextElementSibling;
        const contentTypeSelect = document.getElementById('contentType');
        const customTextArea = modal.querySelector('.custom-text-area');
        const customTextInput = document.getElementById('customText');
        
        // 重置表单
        form.reset();
        
        // 如果是编辑模式，填充数据
        if (pattern) {
            buttonNameInput.value = pattern.buttonName || pattern.pattern || '';
            patternInput.value = pattern.pattern || '';
            backendInput.value = pattern.backendUrl || '';
            shortcutInput.value = pattern.shortcut || '';
            contentTypeSelect.value = pattern.contentType || 'custom';
            
            if (pattern.contentType === 'custom' && pattern.customText) {
                customTextInput.value = pattern.customText;
            }
        }
        
        // 根据当前内容类型显示/隐藏自定义文本区域
        if (contentTypeSelect.value === 'custom') {
            customTextArea.classList.add('active');
        } else {
            customTextArea.classList.remove('active');
        }
        
        // 显示模态框
        modal.classList.add('active');
        
        // 快捷键输入框点击事件
        shortcutInput.addEventListener('click', () => {
            if (!isRecording) {
                isRecording = true;
                currentShortcutInput = shortcutInput;
                shortcutInput.classList.add('recording');
                shortcutInput.placeholder = '请按下快捷键...';
                pressedKeys.clear();
            }
        });
        
        // 清除快捷键按钮事件
        shortcutClearBtn.addEventListener('click', () => {
            shortcutInput.value = '';
            shortcutInput.placeholder = '点击此处设置快捷键';
            shortcutInput.classList.remove('recording');
            isRecording = false;
            pressedKeys.clear();
            currentShortcutInput = null;
        });
        
        // 监听键盘事件
        document.addEventListener('keydown', (e) => {
            if (!isRecording || !currentShortcutInput) return;
            
            // 阻止默认行为
            e.preventDefault();
            
            // 获取按键组合
            const key = e.key.toLowerCase();
            if (key === 'escape') {
                // ESC键取消录制
                isRecording = false;
                currentShortcutInput.classList.remove('recording');
                currentShortcutInput.placeholder = '点击此处设置快捷键';
                pressedKeys.clear();
                currentShortcutInput = null;
                return;
            }
            
            // 添加修饰键
            if (e.ctrlKey) pressedKeys.add('ctrl');
            if (e.shiftKey) pressedKeys.add('shift');
            if (e.altKey) pressedKeys.add('alt');
            if (e.metaKey) pressedKeys.add('meta');
            
            // 添加主键
            if (!['control', 'shift', 'alt', 'meta'].includes(key)) {
                pressedKeys.add(key);
            }
            
            // 更新显示
            const shortcut = Array.from(pressedKeys).join('+');
            currentShortcutInput.value = shortcut;
        });
        
        // 监听键盘释放事件
        document.addEventListener('keyup', (e) => {
            if (!isRecording || !currentShortcutInput) return;
            
            const key = e.key.toLowerCase();
            if (['control', 'shift', 'alt', 'meta'].includes(key)) {
                pressedKeys.delete(key);
            }
            
            // 更新显示
            const shortcut = Array.from(pressedKeys).join('+');
            currentShortcutInput.value = shortcut;
        });
        
        // 内容类型选择事件
        contentTypeSelect.addEventListener('change', () => {
            if (contentTypeSelect.value === 'custom') {
                customTextArea.classList.add('active');
            } else {
                customTextArea.classList.remove('active');
            }
        });
        
        // 关闭按钮事件
        const closeBtn = modal.querySelector('.url-pattern-modal-close');
        closeBtn.onclick = () => {
            modal.classList.remove('active');
            // 清理快捷键捕获状态
            isRecording = false;
            pressedKeys.clear();
            currentShortcutInput = null;
        };
        
        // 取消按钮事件
        const cancelBtn = modal.querySelector('.modal-btn.cancel');
        cancelBtn.onclick = () => {
            modal.classList.remove('active');
            // 清理快捷键捕获状态
            isRecording = false;
            pressedKeys.clear();
            currentShortcutInput = null;
        };
        
        // 表单提交事件
        form.onsubmit = (e) => {
            e.preventDefault();
            
            const buttonName = buttonNameInput.value.trim();
            const patternValue = patternInput.value.trim();
            const backendValue = backendInput.value.trim();
            const shortcutValue = shortcutInput.value.trim();
            const contentType = contentTypeSelect.value;
            let customText = '';
            
            if (!buttonName || !patternValue || !backendValue) {
                showError('请填写按钮名称、URL模式和后端地址');
                return;
            }
            
            if (contentType === 'custom') {
                customText = customTextInput.value.trim();
                if (!customText) {
                    showError('请填写自定义文本');
                    return;
                }
            }
            
            // 创建配置项
            const patternData = {
                buttonName,
                pattern: patternValue,
                backendUrl: backendValue,
                shortcut: shortcutValue,
                contentType
            };
            
            if (contentType === 'custom') {
                patternData.customText = customText;
            }
            
            // 更新或添加配置
            const row = pattern ? 
                Array.from(urlPatternsContainer.children).find(r => r.dataset.pattern === pattern.pattern) : 
                null;
            
            if (row) {
                row.dataset.buttonName = buttonName;
                row.dataset.pattern = patternValue;
                row.dataset.backendUrl = backendValue;
                row.dataset.shortcut = shortcutValue;
                row.dataset.contentType = contentType;
                if (contentType === 'custom') {
                    row.dataset.customText = customText;
                }
                row.querySelector('.pattern-name-container').textContent = buttonName;
            } else {
                addUrlPatternRow(patternData);
            }
            
            saveUrlPatterns();
            modal.classList.remove('active');
            // 清理快捷键捕获状态
            isRecording = false;
            pressedKeys.clear();
            currentShortcutInput = null;
        };
    }
    
    // 添加URL模式按钮事件
    addUrlPatternBtn.addEventListener('click', () => {
        showUrlPatternModal();
    });
    
    // 保存URL模式配置
    async function saveUrlPatterns() {
        try {
            console.log('开始保存URL模式配置');
            
            // 获取所有URL模式行
            const rows = document.querySelectorAll('.url-pattern-row');
        const patterns = [];
            
            // 遍历每一行获取数据
            rows.forEach((row) => {
                const nameContainer = row.querySelector('.pattern-name-container');
                
                // 从data-*属性中获取值
                const pattern = row.dataset.pattern;
                const backendUrl = row.dataset.backendUrl;
                const shortcut = row.dataset.shortcut;
                const buttonName = row.dataset.buttonName || nameContainer.textContent;
                const contentType = row.dataset.contentType || 'cookies';
                const customText = row.dataset.customText || '';
                
                if (pattern && backendUrl) {
                    console.log('添加配置:', {
                        pattern,
                        backendUrl,
                        shortcut,
                        buttonName,
                        contentType,
                        customText: customText.substring(0, 20) + (customText.length > 20 ? '...' : '')
                    });
                    
                    patterns.push({
                        pattern,
                        backendUrl,
                        shortcut: shortcut || null,
                        buttonName: buttonName || pattern,
                        contentType: contentType || 'cookies',
                        customText: customText || ''
                    });
                }
            });
            
            console.log(`保存${patterns.length}个URL模式配置`);
            
            // 保存到存储
            await chrome.storage.sync.set({ urlPatterns: patterns });
            console.log('URL模式配置已保存');
            
            // 检查保存是否成功
            const result = await chrome.storage.sync.get(['urlPatterns']);
            console.log('保存后检查配置:', result.urlPatterns);
        } catch (error) {
            console.error('保存URL模式配置失败:', error);
            alert('保存失败：' + error.message);
        }
    }
    
    // 显示加载状态
    function showLoading(progress = 0) {
        loadingElement.classList.add('active');
        progressBarFill.style.width = `${progress}%`;
    }
    
    // 隐藏加载状态
    function hideLoading() {
        loadingElement.classList.remove('active');
        progressBarFill.style.width = '0%';
    }
    
    // 更新进度
    function updateProgress(progress) {
        progressBarFill.style.width = `${progress}%`;
    }
    
    // 发送消息到content script
    async function sendMessageToContentScript(action, data = {}) {
        return new Promise((resolve, reject) => {
            const maxRetries = 3;
            let retryCount = 0;

            const trySendMessage = async () => {
                try {
                    const tabs = await new Promise(resolve => {
                        chrome.tabs.query({active: true, currentWindow: true}, resolve);
                    });

                    if (!tabs[0]) {
                        throw new Error('未找到活动标签页');
                    }

                    // 确保content script已注入
                    await chrome.scripting.executeScript({
                        target: { tabId: tabs[0].id },
                        files: ['content.js']
                    });

                    return new Promise((resolve, reject) => {
                        chrome.tabs.sendMessage(tabs[0].id, {
                            action,
                            ...data
                        }, (response) => {
                            if (chrome.runtime.lastError) {
                                if (retryCount < maxRetries) {
                                    retryCount++;
                                    setTimeout(trySendMessage, 1000);
                                } else {
                                    reject(new Error(chrome.runtime.lastError.message));
                                }
                            } else if (!response || !response.success) {
                                reject(new Error(response?.error || '操作失败'));
                            } else {
                                resolve(response);
                            }
                        });
                    });
                } catch (error) {
                    if (retryCount < maxRetries) {
                        retryCount++;
                        setTimeout(trySendMessage, 1000);
                    } else {
                        reject(error);
                    }
                }
            };

            trySendMessage();
        });
    }
    
    // 显示错误提示
    function showError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.style.cssText = `
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #ff5252;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            z-index: 10000;
        `;
        errorDiv.textContent = message;
        document.body.appendChild(errorDiv);
        setTimeout(() => errorDiv.remove(), 3000);
    }
    
    // 显示成功提示
    function showSuccess(message) {
        const successDiv = document.createElement('div');
        successDiv.className = 'success-message';
        successDiv.textContent = message;
        document.body.appendChild(successDiv);
        setTimeout(() => successDiv.remove(), 3000);
    }
    
    // 更新按钮状态
    function updateButtonStates() {
        const hasApiKey = apiKeyInput.value.trim() !== '';
        const hasBaseUrl = baseUrlInput.value.trim() !== '';
        
        translatePageBtn.disabled = !hasApiKey || !hasBaseUrl;
        summarizePageBtn.disabled = !hasApiKey || !hasBaseUrl;
        translateAndSummarizeBtn.disabled = !hasApiKey || !hasBaseUrl;
        // 导入导出按钮始终可用
        importDataBtn.disabled = false;
        exportDataBtn.disabled = false;
        saveSettingsBtn.disabled = !hasApiKey || !hasBaseUrl;
    }
    
    // 保存设置
    async function saveSettings() {
        const apiKey = apiKeyInput.value.trim();
        const baseUrl = baseUrlInput.value.trim();
        const modelName = modelNameInput.value.trim();
        
        if (!apiKey) {
            showError('请输入API密钥');
            return;
        }
        
        if (!baseUrl) {
            showError('请输入基础URL');
            return;
        }
        
        if (!modelName) {
            showError('请输入模型名称');
            return;
        }
        
        try {
            await chrome.storage.sync.set({
                apiKey,
                baseUrl,
                modelName,
                autoTranslate: autoTranslateCheckbox.checked,
                saveHistory: saveHistoryCheckbox.checked,
                urlPatterns: getUrlPatterns()
            });
            showSuccess('设置已保存');
            updateButtonStates();
        } catch (error) {
            showError('保存设置失败');
            console.error('保存设置失败:', error);
        }
    }
    
    // 按钮点击事件处理
    translatePageBtn.addEventListener('click', async () => {
        try {
            showLoading();
            await sendMessageToContentScript('translatePage');
            hideLoading();
        } catch (error) {
            console.error('翻译失败:', error);
            hideLoading();
            showError(error.message || '翻译失败，请重试');
        }
    });
    
    summarizePageBtn.addEventListener('click', async () => {
        try {
            showLoading();
            await sendMessageToContentScript('summarizePage');
            hideLoading();
        } catch (error) {
            console.error('总结失败:', error);
            hideLoading();
            showError(error.message || '总结失败，请重试');
        }
    });
    
    translateAndSummarizeBtn.addEventListener('click', async () => {
        try {
            showLoading();
            await sendMessageToContentScript('summarizeAndTranslate');
            hideLoading();
        } catch (error) {
            console.error('翻译和总结失败:', error);
            hideLoading();
            showError(error.message || '翻译和总结失败，请重试');
        }
    });
    
    importDataBtn.addEventListener('click', async () => {
        try {
            // 创建文件选择器
            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.accept = '.json';
            
            // 监听文件选择
            fileInput.onchange = async (event) => {
                const file = event.target.files[0];
                if (!file) return;
                
                // 显示加载状态
                showLoading();
                
                try {
                    // 读取文件内容
                    const fileReader = new FileReader();
                    
                    fileReader.onload = async (e) => {
                        try {
                            const jsonData = JSON.parse(e.target.result);
                            
                            // 验证数据格式
                            if (!jsonData || typeof jsonData !== 'object') {
                                throw new Error('无效的数据格式');
                            }
                            
                            // 导入设置
                            if (jsonData.settings) {
                                const settings = jsonData.settings;
                                
                                // 更新UI
                                if (settings.autoTranslate !== undefined) autoTranslateCheckbox.checked = settings.autoTranslate;
                                if (settings.saveHistory !== undefined) saveHistoryCheckbox.checked = settings.saveHistory;
                                if (settings.apiKey) apiKeyInput.value = settings.apiKey;
                                if (settings.baseUrl) baseUrlInput.value = settings.baseUrl;
                                if (settings.modelName) modelNameInput.value = settings.modelName;
                                
                                // 直接保存设置到存储，不进行验证
                                await chrome.storage.sync.set({
                                    apiKey: settings.apiKey || '',
                                    baseUrl: settings.baseUrl || '',
                                    modelName: settings.modelName || '',
                                    autoTranslate: settings.autoTranslate || false,
                                    saveHistory: settings.saveHistory || false
                                });
                            }
                            
                            // 导入URL模式
                            if (jsonData.urlPatterns && Array.isArray(jsonData.urlPatterns)) {
                                // 先清空当前列表
                                urlPatternsContainer.innerHTML = '';
                                
                                // 添加导入的模式
                                jsonData.urlPatterns.forEach(pattern => {
                                    addUrlPatternRow(pattern);
                                });
                                
                                // 保存到存储
                                await saveUrlPatterns();
                            }
                            
                            hideLoading();
                            showSuccess('数据导入成功');
                        } catch (error) {
                            hideLoading();
                            showError('导入数据解析失败: ' + error.message);
                        }
                    };
                    
                    fileReader.onerror = () => {
                        hideLoading();
                        showError('读取文件失败');
                    };
                    
                    // 开始读取文件
                    fileReader.readAsText(file);
                } catch (error) {
                    hideLoading();
                    showError('处理文件失败: ' + error.message);
                }
            };
            
            // 触发文件选择器
            fileInput.click();
        } catch (error) {
            console.error('数据导入失败:', error);
            hideLoading();
            showError(error.message || '数据导入失败，请重试');
        }
    });
    
    exportDataBtn.addEventListener('click', async () => {
        try {
            showLoading();
            
            // 收集当前设置
            const settings = {
                autoTranslate: autoTranslateCheckbox.checked,
                saveHistory: saveHistoryCheckbox.checked,
                apiKey: apiKeyInput.value,
                baseUrl: baseUrlInput.value,
                modelName: modelNameInput.value
            };
            
            // 收集URL模式
            const urlPatterns = getUrlPatterns();
            
            // 创建导出数据
            const exportData = {
                settings: settings,
                urlPatterns: urlPatterns,
                exportDate: new Date().toISOString()
            };
            
            // 转换为JSON
            const jsonData = JSON.stringify(exportData, null, 2);
            
            // 创建下载
            const blob = new Blob([jsonData], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = url;
            a.download = `chrome-extension-settings-${new Date().toISOString().slice(0, 10)}.json`;
            document.body.appendChild(a);
            a.click();
            
            // 清理
            setTimeout(() => {
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }, 100);
            
            hideLoading();
            showSuccess('数据导出成功');
        } catch (error) {
            console.error('数据导出失败:', error);
            hideLoading();
            showError(error.message || '数据导出失败，请重试');
        }
    });
    
    // 在保存设置时同时保存URL模式
    saveSettingsBtn.addEventListener('click', async () => {
        await saveUrlPatterns();
        await saveSettings();
    });
    
    // 输入框验证
    function validateInputs() {
        const apiKey = apiKeyInput.value.trim();
        const baseUrl = baseUrlInput.value.trim();
        
        saveSettingsBtn.disabled = !apiKey || !baseUrl;
    }
    
    // 监听输入变化
    apiKeyInput.addEventListener('input', validateInputs);
    baseUrlInput.addEventListener('input', validateInputs);
    
    // 初始验证
    validateInputs();
    
    // 初始化快捷键录制功能
    setupShortcutRecording();
});

// 添加快捷键监听器
function setupShortcutListener() {
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
        if (request.action === 'checkShortcut') {
            chrome.storage.sync.get(['urlPatterns'], (result) => {
                const patterns = result.urlPatterns || [];
                const matchingPattern = patterns.find(p => p.shortcut === request.shortcut);
                if (matchingPattern) {
                    sendResponse({ 
                        found: true, 
                        pattern: matchingPattern.pattern,
                        backendUrl: matchingPattern.backendUrl
                    });
                } else {
                    sendResponse({ found: false });
                }
            });
            return true; // 保持消息通道开放
        }
    });
}

// 获取所有URL模式配置
function getUrlPatterns() {
    const patterns = [];
    const container = document.getElementById('urlPatterns');
    if (!container) return patterns;
    
    const rows = container.querySelectorAll('.url-pattern-row');
    
    rows.forEach(row => {
        const buttonName = row.dataset.buttonName;
        const pattern = row.dataset.pattern;
        const backendUrl = row.dataset.backendUrl;
        const shortcut = row.dataset.shortcut;
        const contentType = row.dataset.contentType || 'cookies';
        const customText = row.dataset.customText || '';
        
        if (pattern && backendUrl) {
            patterns.push({
                buttonName,
                pattern,
                backendUrl,
                shortcut: shortcut || null,
                contentType,
                customText
            });
        }
    });
    
    return patterns;
}

// 显示编辑模态框
function showEditModal(row) {
    const modal = document.getElementById('editModal');
    const closeBtn = modal.querySelector('.close-button');
    const saveBtn = modal.querySelector('#saveEditButton');
    
    // 填充表单数据
    const patternInput = modal.querySelector('input[name="pattern"]');
    const backendUrlInput = modal.querySelector('input[name="backendUrl"]');
    const shortcutInput = modal.querySelector('input[name="shortcut"]');
    const buttonNameInput = modal.querySelector('input[name="buttonName"]');
    const contentTypeSelect = modal.querySelector('select[name="contentType"]');
    const customTextArea = modal.querySelector('textarea[name="customText"]');
    
    // 添加shortcut-input类以启用录制功能
    shortcutInput.classList.add('shortcut-input');
    
    // 从行元素获取数据
    patternInput.value = row.dataset.pattern || '';
    backendUrlInput.value = row.dataset.backendUrl || '';
    shortcutInput.value = row.dataset.shortcut || '';
    buttonNameInput.value = row.dataset.buttonName || '';
    contentTypeSelect.value = row.dataset.contentType || 'cookies';
    customTextArea.value = row.dataset.customText || '';
    
    // 根据内容类型显示/隐藏自定义文本区域
    toggleCustomTextArea(contentTypeSelect.value);
    
    // 显示模态框
    modal.style.display = 'block';
    
    // 关闭按钮事件
    closeBtn.onclick = function() {
        modal.style.display = 'none';
        // 移除shortcut-input类以避免重复添加
        shortcutInput.classList.remove('shortcut-input');
    };
    
    // 点击模态框外部关闭
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = 'none';
            // 移除shortcut-input类以避免重复添加
            shortcutInput.classList.remove('shortcut-input');
        }
    };
    
    // 内容类型变更事件
    contentTypeSelect.onchange = function() {
        toggleCustomTextArea(this.value);
    };
    
    // 保存按钮事件
    saveBtn.onclick = function() {
        // 表单验证
        const pattern = patternInput.value.trim();
        const backendUrl = backendUrlInput.value.trim();
        let isValid = true;
        
        if (!pattern) {
            alert('请输入URL模式');
            isValid = false;
        }
        
        if (!backendUrl) {
            alert('请输入后端地址');
            isValid = false;
        }
        
        if (!isValid) return;
        
        // 更新行元素数据
        row.dataset.pattern = pattern;
        row.dataset.backendUrl = backendUrl;
        row.dataset.shortcut = shortcutInput.value;
        row.dataset.buttonName = buttonNameInput.value;
        row.dataset.contentType = contentTypeSelect.value;
        row.dataset.customText = customTextArea.value;
        
        // 更新显示的名称
        const nameContainer = row.querySelector('.pattern-name-container');
        nameContainer.textContent = buttonNameInput.value || pattern;
        
        // 保存到存储
        saveUrlPatterns();
        
        // 关闭模态框
        modal.style.display = 'none';
        // 移除shortcut-input类以避免重复添加
        shortcutInput.classList.remove('shortcut-input');
    };
}

// 显示添加模态框
function showAddModal() {
    const modal = document.getElementById('addModal');
    const closeBtn = modal.querySelector('.close-button');
    const saveBtn = modal.querySelector('#saveButton');
    
    // 获取表单元素
    const patternInput = modal.querySelector('input[name="pattern"]');
    const backendUrlInput = modal.querySelector('input[name="backendUrl"]');
    const shortcutInput = modal.querySelector('input[name="shortcut"]');
    const buttonNameInput = modal.querySelector('input[name="buttonName"]');
    const contentTypeSelect = modal.querySelector('select[name="contentType"]');
    const customTextArea = modal.querySelector('textarea[name="customText"]');
    
    // 添加shortcut-input类以启用录制功能
    shortcutInput.classList.add('shortcut-input');
    
    // 重置表单
    patternInput.value = '';
    backendUrlInput.value = '';
    shortcutInput.value = '';
    buttonNameInput.value = '';
    contentTypeSelect.value = 'cookies';
    customTextArea.value = '';
    
    // 根据内容类型显示/隐藏自定义文本区域
    toggleCustomTextArea(contentTypeSelect.value);
    
    // 显示模态框
    modal.style.display = 'block';
    
    // 关闭按钮事件
    closeBtn.onclick = function() {
        modal.style.display = 'none';
        // 移除shortcut-input类以避免重复添加
        shortcutInput.classList.remove('shortcut-input');
    };
    
    // 点击模态框外部关闭
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = 'none';
            // 移除shortcut-input类以避免重复添加
            shortcutInput.classList.remove('shortcut-input');
        }
    };
    
    // 内容类型变更事件
    contentTypeSelect.onchange = function() {
        toggleCustomTextArea(this.value);
    };
    
    // 保存按钮事件
    saveBtn.onclick = function() {
        // 表单验证
        const pattern = patternInput.value.trim();
        const backendUrl = backendUrlInput.value.trim();
        let isValid = true;
        
        if (!pattern) {
            alert('请输入URL模式');
            isValid = false;
        }
        
        if (!backendUrl) {
            alert('请输入后端地址');
            isValid = false;
        }
        
        if (!isValid) return;
        
        // 创建新的配置行
        addUrlPattern({
            pattern: pattern,
            backendUrl: backendUrl,
            shortcut: shortcutInput.value,
            buttonName: buttonNameInput.value || pattern,
            contentType: contentTypeSelect.value,
            customText: customTextArea.value
        });
        
        // 保存到存储
        saveUrlPatterns();
        
        // 关闭模态框
        modal.style.display = 'none';
        // 移除shortcut-input类以避免重复添加
        shortcutInput.classList.remove('shortcut-input');
    };
} 